import configparser
import time
import xml.etree.ElementTree as ET
import os

# 全局变量，记录api个数
x = 1

# JMeter.bat地址
JMETER_BAT_Home = "C:\\Users\\admin\Desktop\\apache-jmeter-5.2.1\\bin\jmeter.bat"

# 当前文件路径
CURRENT_PATH = os.getcwd ()

# jmx生成路径
JMX_API_PATH = CURRENT_PATH + "\\api_jmx\\"

# 测试报告存放地址(需要目录存在）
REPORT_PATH = CURRENT_PATH + "\\report\\"

# 测试结果地址(需要目录存在）
RESULT_PATH = CURRENT_PATH + "\\result\\"

htmlreport_list = []
jmxfile_name_list = []

# 检查路径是否存在
# 不存在就新建
def checkPath(path):
    if os.path.exists(path):
        pass
    else:
        os.makedirs(path)


# 读取并从模板中编辑生成JMX文件
def editJMX(jmxFile, ip, port, path, param, loops, num_threads, ramp_time):
    tree = ET.parse (jmxFile)
    root = tree.getroot ()  # Reading the file from disk

    # 获取要修改的标签
    s_loop = root.find (".//*[@name='LoopController.loops']")
    s_num_threads = root.find (".//*[@name='ThreadGroup.num_threads']")
    s_ramp_time = root.find (".//*[@name='ThreadGroup.ramp_time']")
    s_domain = root.find (".//*[@name='HTTPSampler.domain']")
    s_port = root.find (".//*[@name='HTTPSampler.port']")
    s_path = root.find (".//*[@name='HTTPSampler.path']")
    s_param = root.find (".//*[@name='Argument.value']")

    # 修改标签内容
    s_domain.text = str (ip)
    s_port.text = str (port)
    s_path.text = str (path)
    s_param.text = str (param)
    s_loop.text = str (loops)
    s_num_threads.text = str (num_threads)
    s_ramp_time.text = str (ramp_time)
    tree.write ('api_jmx/api' + str (x) + '.jmx')  # 只能用加号，逗号出错


# 拆分一行api数据
# 主机/路径/参数
def splitData(data):
    host, path, data = data.split ('$', 2)  # 以$分割两次
    ip, port = host.split (':', 1)  # 以:分割一次
    return ip, port, path, data


# 执行命令行运行jmx非GUI界面脚本测试
def excuteJMX():
    for n in range (1, x):
        now = getDateTime() # 获取当前时间
        api_name = "api" + str (n)  # api的名字
        name = now + api_name   # 报告结果名
        # 执行jmx
        run ="jmeter -n -t " + JMX_API_PATH + api_name + ".jmx"
        # run = JMETER_BAT_Home + " -n -t " + JMX_API_PATH + api_name + ".jmx"
        # 生成并存储测试结果和报告
        generate_result = " -l" + RESULT_PATH + name + "_result.jsl -e -o " + REPORT_PATH + name
        cmd = run + generate_result
        os.system (cmd)


#  获取当前时间，用于命名
def getDateTime():
    '''
    获取当前日期时间，格式'20150708_085159'
    '''
    return time.strftime(r'%Y%m%d_%H%M%S_', time.localtime(time.time()))


# 生成报告汇总html页面
def createHtml(htmlFile):
    htmltree = ET.parse (htmlFile)
    root = htmltree.getroot ()  # Reading the file from disk

    # 获取要修改的div标签
    div = root.find (".//*[@name='reportTable']")

    # 获取html内容
    for root, dirs, files in os.walk (REPORT_PATH):
        for name in dirs:
            print(name)



    # 整理内容
    # 标题
    title = ['执行时间', 'jmx文件', '响应结果', '报告详情']
    th_str = '<tr>' # 标题行
    for x in title:
        th_str = th_str + '<th>' + x + '</th>'
    else:
        th_str = th_str + '</tr>'

    tableContent = ""

    div.text = str (tableContent)  # .text 修改值
    pass

if __name__ == '__main__':
    # 〇、检查路径是否存在（不存在则新增）
    checkPath(JMX_API_PATH)
    checkPath(REPORT_PATH)
    checkPath(RESULT_PATH)

    # 一、读配置文件settings.ini
    cf = configparser.ConfigParser ()
    cf.read (CURRENT_PATH + '\settings.ini', encoding='UTF-8')
    print(cf.sections())

    # 1.线程配置内容(read int)
    number_of_threads = cf.getint ("common_set", "number_of_threads")
    ramp_up_period = cf.getint ("common_set", "ramp_up_period")
    loop_count = cf.getint ("common_set", "loop_count")

    # 2.接口数据地址
    api_path = cf.get ("api_path", "api_data")
    print ('api详情文件地址：', api_path)

    api_cf = configparser.ConfigParser ()
    api_cf.read (CURRENT_PATH + "\\" +api_path)

    # 二、读取api配置详情
    api_cf = configparser.ConfigParser ()
    # api_cf.read (api_path, encoding="UTF-8")
    api_cf.read (api_path)
    # 获取每行api详情
    for item in api_cf["api_test"]:
        api_data = api_cf.get ("api_test", item)
        ip, port, path, data = splitData (api_data)
        # 三、编辑JMX文件
        jmxName = 'api_jmx/api_demo.jmx'
        editJMX (jmxName, ip, port, path, data, loop_count, number_of_threads, ramp_up_period)
        x += 1
        print (x)

    # 四、执行JMX
    excuteJMX ()

    # htmlName = "reportIndex.html"
    # createHtml(htmlName)
